package com.numberone.master.modules.Interfaces.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.drew.lang.annotations.Nullable;
import com.numberone.master.common.Interface.YiDong;
import com.numberone.master.common.encryption.RSAUtils;
import com.numberone.master.common.exception.BizException;
import com.numberone.master.common.lianlianpay.base.PartnerConfig;
import com.numberone.master.common.lianlianpay.util.YinTongUtil;
import com.numberone.master.common.lianlianpay.vo.PayDataBean;
import com.numberone.master.common.menu.RespCode;
import com.numberone.master.common.utils.BASE64;
import com.numberone.master.common.utils.DateUtils;
import com.numberone.master.common.utils.DoubleUtil;
import com.numberone.master.common.utils.JsonUtils;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.common.zhifubao.AlipayUtil;
import com.numberone.master.modules.Interfaces.entity.FlowInfo;
import com.numberone.master.modules.card.dao.CardAmountDao;
import com.numberone.master.modules.card.dao.CardRechargeFlowDao;
import com.numberone.master.modules.card.entity.Card;
import com.numberone.master.modules.card.entity.CardAmount;
import com.numberone.master.modules.card.entity.CardRechargeFlow;
import com.numberone.master.modules.card.service.CardAmountService;
import com.numberone.master.modules.card.service.CardRechargeFlowService;
import com.numberone.master.modules.card.service.CardService;
import com.numberone.master.modules.orders.dao.RechargeOrderDao;
import com.numberone.master.modules.orders.dao.WithdrawalsOrderDao;
import com.numberone.master.modules.orders.entity.RechargeOrder;
import com.numberone.master.modules.orders.entity.WithdrawalsOrder;
import com.numberone.master.modules.orders.service.RechargeOrderService;
import com.numberone.master.modules.orders.service.WithdrawalsOrderService;
import com.numberone.master.modules.profit.entity.Account;
import com.numberone.master.modules.profit.entity.AccountInfo;
import com.numberone.master.modules.profit.service.AccountInfoService;
import com.numberone.master.modules.profit.service.AccountService;
import com.numberone.master.modules.recharge.service.PackageService;
import com.numberone.master.modules.recharge.service.RechargeLsService;
import com.numberone.master.modules.rsa.entity.RsaKey;
import com.numberone.master.modules.rsa.service.RsaService;
import com.numberone.master.modules.sys.dao.OfficeCardDao;
import com.numberone.master.modules.sys.entity.DictInfo;
import com.numberone.master.modules.sys.entity.Office;
import com.numberone.master.modules.sys.entity.OfficeCard;
import com.numberone.master.modules.sys.entity.User;
import com.numberone.master.modules.sys.service.DictService;
import com.numberone.master.modules.sys.service.OfficeService;
import com.numberone.master.modules.sys.service.SystemService;
import com.numberone.master.modules.sys.utils.UserUtils;
import com.numberone.master.modules.recharge.entity.Package;
import com.numberone.master.modules.recharge.entity.RechargeLs;


/**
 * 物联网卡Service
 * @author chegkang
 * @version 2018-02-01
 */
@Service
@Transactional(readOnly = true)
public class WLWKService {
	
	@Autowired
	private CardService cardService;
	@Autowired
	private RsaService rsaService;
	@Autowired
	private PackageService packageService;
	@Autowired
	private DictService dictService;
	@Autowired
	private OfficeCardDao officeCardDao;
	@Autowired
	RechargeOrderDao rechargeOrderDao;
	@Autowired
	private WithdrawalsOrderDao withdrawalsOrderDao;
	@Autowired
	private AccountInfoService accountInfoService;
	@Autowired
	private CardRechargeFlowDao cardRechargeFlowDao;
	@Autowired
	private CardAmountDao cardAmountDao;
	
	
	public static final String MONEY = "^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$";

	
	public List<Package> packList(String iccid) {
		if(StringUtils.isBlank(iccid)){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		Card card = cardService.getCardInfoByCCID(iccid);
		if(card == null){
			throw new BizException("-1","iccid不存在。");
		}
		String areaId = card.getAreaId();
		//查询卡的所属人
		OfficeCard officeCard = officeCardDao.selectThePeople(card.getId());
		if(officeCard == null){
			throw new BizException("-1","未查询到卡的所属代理商");
		}
		String officeId = officeCard.getOfficeId();
		//青岛卡暂时没有默认的套餐
		List<Package> list = new ArrayList<>();
		String pkg = card.getPkg();
		Package p = packageService.getTaocan2ByStoreid(officeId, pkg);
		if(p == null){
			throw new BizException("-1","为查询到所属套餐信息");
		}
		list.add(p);
		if(!StringUtils.equals("7", pkg) && !StringUtils.equals(areaId, "5")){
			Package p2 = packageService.getTaocan2ByStoreid(officeId, "7");
			if(p2 != null){
				list.add(p2);
			}
		}
		return list;
	}

	
	
	public Map<String,Object> getInfosByIccid(String iccid){
		String title = "";
		Map<String,Object> map = new HashMap<>(); 
		if(StringUtils.isBlank(iccid)){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		Card card = cardService.getCardByCCID(iccid, "0");
		if(card == null){
			throw new BizException("-1","iccid错误，没有查询到此流量卡");
		}
		List<DictInfo> list = dictService.getNotDictList("pkg", "0");
		for (DictInfo dic : list) {
			String  dicId = dic.getValue();
			if(StringUtils.equals(dicId, "1")){
    			title = dic.getLabel();
    		}else if(StringUtils.equals(dicId, "2")){
    			title = dic.getLabel();
    		}
		}
		map.put("areaId", card.getAreaId());
		map.put("phone", card.getPhonenumber());
		map.put("title", title);
		map.put("memo1", "");
		map.put("type", card.getType());
		return map;
	}
	
	public String findYuEByICCID(String iccid){
		if(StringUtils.isBlank(iccid)){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		//查询卡
		Card card = cardService.getCardByCCID(iccid, "0");
		if(card == null){
			throw new BizException("-1","iccid错误，没有查询到此流量卡");
		}
		String areaId = card.getAreaId();//卡所属地区
		String transid = rsaService.getTransid();
		if(StringUtils.isBlank(areaId)){
			throw new BizException("-1","此卡所属地区不明确，查询失败");
		}
		String res = YiDong.yiDongPost("0001000000035", areaId, iccid, transid);
		return res;
	}
	
	@Transactional(readOnly = false)
	public Map<String,Object> update(HttpServletRequest req) {
        System.out.println("进入物联网付款异步通知数据接收处理============================");
		Map<String,Object> map = new HashMap<>();
       String reqStr = YinTongUtil.readReqStr(req);
        if (YinTongUtil.isnull(reqStr)){
			//可抛异常，后续人工介入分析原因,这里的交易失败不是指订单付款失败，订单付款结果以订单付款状态字段result_pay为准
        	map.put("ret_code", "9999");
        	map.put("ret_msg", "交易失败");
            return map;
        }
        System.out.println("物联网提现接收付款异步通知数据=======：【" + reqStr + "】");
        if (!YinTongUtil.checkSign(reqStr, PartnerConfig.YT_PUB_KEY,PartnerConfig.MD5_KEY)){
			//可抛异常，后续人工介入分析原因,这里的交易失败不是指订单付款失败，订单付款结果以订单付款状态字段result_pay为准
        	map.put("ret_code", "9999");
        	map.put("ret_msg", "交易失败");
            System.out.println("付款异步通知验签失败");
            return map;
        }
        map.put("ret_code", "0000");
    	map.put("ret_msg", "交易成功");
        System.out.println("==================物联网提现接收付款异步通知数据顶顶那修改================");
        //解析异步通知对象
        PayDataBean payDataBean = JSON.parseObject(reqStr, PayDataBean.class);
        String resultPay = payDataBean.getResult_pay();//订单状态
        String orderNo = payDataBean.getNo_order();//订单号
        String moneyOrder = payDataBean.getMoney_order();
        System.out.println("订单号=============="+orderNo);
        System.out.println("订单状态=============="+resultPay);
        //查询卡友提交的订单
        WithdrawalsOrder order = withdrawalsOrderDao.selectWitOrderByNo(orderNo);
        if(order != null){
        	if(StringUtils.equals(order.getState(), "1")){
        		String price = order.getWithdrwalsAmount();//交易金额
            	String officeId = order.getOfficeId();//所属人
            	//查询所属账户
            	AccountInfo accountInfo = accountInfoService.getAccountByOfficeId(officeId);
            	Double memory = Double.valueOf(price);//订单金额
        		Double kamtMoney = Double.valueOf(accountInfo.getKamt());//现有金额
        		Double damt = Double.valueOf(accountInfo.getDamt());//冻结金额
                if("SUCCESS".equals(resultPay)){
                	System.out.println("订单成功=============="+resultPay);
                	//**成功订单**//*
            		accountInfo.setDamt(String.valueOf(DoubleUtil.sub(damt, memory)));//扣除冻结金额
            		accountInfoService.update(accountInfo);
            		//订单状态设置
            		order.setState("4");
            		order.setUpdateById("1");
            		order.setUpdateDate(new Date());
            		order.setRemarks(order.getRemarks()+"_成功");
            		withdrawalsOrderDao.update(order);
                }else{
                	System.out.println("订单失败=============="+resultPay);
                	//**失败订单**//*
            		accountInfo.setDamt(String.valueOf(DoubleUtil.sub(damt, memory)));//扣除冻结金额
            		accountInfo.setKamt(String.valueOf(DoubleUtil.add(kamtMoney, memory)));
            		accountInfoService.update(accountInfo);
            		//订单状态设置
            		order.setState("5");
            		order.setUpdateById("1");
            		order.setUpdateDate(new Date());
            		order.setRemarks(order.getRemarks()+resultPay+"_"+payDataBean.getInfo_order());
            		withdrawalsOrderDao.update(order);
                }
            }
        }else{
        	//没有订单，添加异常的订单信息
        	WithdrawalsOrder withdrawalsOrder = new WithdrawalsOrder();
        	withdrawalsOrder.setState("2");
        	withdrawalsOrder.setCreateById("1");
        	withdrawalsOrder.setUpdateById("1");
        	withdrawalsOrder.setUpdateDate(new Date());
        	withdrawalsOrder.setCreateDate(new Date());
        	withdrawalsOrder.setWithdrwalsAmount(moneyOrder);
        	withdrawalsOrder.setArrivalAmount(moneyOrder);
        	withdrawalsOrder.setOrderNo(orderNo);
        	withdrawalsOrder.setRemarks("物联网卡提现未知订单");
        	withdrawalsOrder.setState("5");
        	withdrawalsOrder.setOfficeId("1");
    		withdrawalsOrderDao.update(withdrawalsOrder);
        }
		return map;
	}
	
	public Map<String,Object> getMposIndex(String iccid){
		Map<String,Object> map = new HashMap<>();
		if(StringUtils.isBlank(iccid)){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		//查询卡
		Card card = cardService.getCardByCCID(iccid, "0");
		if(card == null){
			throw new BizException("9990","iccid错误，没有查询到此流量卡");
		}
		String areaId = card.getAreaId();//卡所属地区
		String transid = rsaService.getTransid();
		String phonenumbe = card.getPhonenumber();
		String number = "";
		if(StringUtils.isBlank(areaId)){
			throw new BizException("9990","此卡所属地区不明确，查询失败");
		}
		if(StringUtils.equals(areaId,"5")){
			number = phonenumbe;
		}else{
			number = iccid;
		}
		//查询流量卡充值记录
		CardRechargeFlow p = new CardRechargeFlow();
		p.setIccid(iccid);
		p.setFlowType(1);
		List<CardRechargeFlow> cardRechargeFlowList = cardRechargeFlowDao.findList(p);
		map.put("recharge_flow_list",cardRechargeFlowList);
		//查询用卡的余额，没有卡信息就添加卡信息
		CardAmount cardAmount = cardAmountDao.selectCardAmountByIccid(iccid);
		if(cardAmount != null){
			cardAmount.setCardId(phonenumbe);
		}
		map.put("card_amount_info",cardAmount);
		//流量卡套餐信息
		FlowInfo flowInfo = YiDong.getPackInfo(number, areaId, transid);
		map.put("flow_info",flowInfo);
		//查询月套餐流量使用情况
		String monthGprs = YiDong.getMonthGprsInfo(number, areaId, transid);
		map.put("month_gprs",monthGprs);
		return map;
	}
	
	
	public String pollingOrder(String orderId){
		if(StringUtils.isBlank(orderId)){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		CardRechargeFlow cardRechargeFlow = cardRechargeFlowDao.selectCardRechargeFlow(orderId);
		if(cardRechargeFlow == null){
			throw new BizException("9990","未查询到此订单，订单错误");
		}
		//查询支付宝的订单状态
		String res = AlipayUtil.payState(orderId);
		return res;
	}
	
	
	public List<CardRechargeFlow> rechargeRecordList(String iccid,Integer type){
		if(StringUtils.isBlank(iccid) || type == null){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		CardRechargeFlow c = new CardRechargeFlow();
		 switch (type) {
         case 1:
        	 c.setFlowType(0);
        	 break; 
         case 2:
        	 c.setFlowType(1);
        	 break; 
         default:
         	throw new BizException("9990","查询类型错误");
		 }
		c.setIccid(iccid);
		return cardRechargeFlowDao.findList(c);
	}
	
	
	@Transactional(readOnly = false)
	public void accountInsertOrder(String iccid,Integer pkgId){
		if(StringUtils.isBlank(iccid) || pkgId == null){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}		
		//查询icc卡余额
		CardAmount cardAmount = cardAmountDao.selectCardAmountByIccid(iccid);
		if(cardAmount == null){
			throw new BizException("9990","iccid错误，未查询到此流量卡");
		}
		//生成订单号
		String orderId = StringUtils.getDateString(6);
		//添加预支付订单
		CardRechargeFlow c = new CardRechargeFlow();
		long nowTime = System.currentTimeMillis();//得到系统时间
		long invalidTime = nowTime += 30*60*1000;//订单失效时间
		//查询卡
		Card card = cardService.getCardByCCID(iccid, "0");
		if(card == null){
			throw new BizException("9990","iccid错误，未查询到此流量卡");
		}
		//查询套餐所属的价格和卡的所属人
		OfficeCard officeCard = officeCardDao.selectThePeople(card.getId());
		if(officeCard == null){
			throw new BizException("9990","未查询到流量卡的所属代理商");
		}
		Package p = packageService.getTaocan2ByStoreid(officeCard.getOfficeId(), String.valueOf(pkgId));
		if(p == null){
			throw new BizException("9990","未查询到此卡的所属套餐价格");
		}
		Double availableAmount = cardAmount.getAvailableAmount();//可用余额
		Double salePrice = p.getSalePrice();//销售价格
		BigDecimal data1 = new BigDecimal(availableAmount);
		BigDecimal data2 = new BigDecimal(salePrice);
		if(data1.compareTo(data2) == -1){
			throw new BizException("9990","充值失败，可用余额不足");
		}
		c.setCreateTime(new Date(nowTime));
		c.setInvalidTime(new Date(invalidTime));
		c.setPkName(p.getTctype());
		c.setAmount(salePrice);
		c.setPackId(pkgId);
		c.setOrderId(orderId);
		c.setIccid(iccid);
		c.setPayType(3);
		c.setFlowType(1);
		c.setPayTime(new Date());
		c.setState(2);
		cardRechargeFlowDao.insert(c);
		//扣除所属icc卡余额
		cardAmountDao.subtractAmount(iccid, salePrice, salePrice);
	}
	
	
	@Transactional(readOnly = false)
	public Map<String,Object> insertOrder(String iccid,Double money,Integer pkgId,int flowType){
		Map<String,Object> map = new HashMap<>();
		//生成订单号
		String orderId = StringUtils.getDateString(6);
		//添加预支付订单
		CardRechargeFlow c = new CardRechargeFlow();
		long nowTime = System.currentTimeMillis();//得到系统时间
		long invalidTime = nowTime += 30*60*1000;//订单失效时间
		if(StringUtils.isBlank(iccid) || money == null){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		//查询icc卡余额
		CardAmount cardAmount = cardAmountDao.selectCardAmountByIccid(iccid);
		if(cardAmount == null){
			throw new BizException("9990","iccid错误，未查询到此流量卡");
		}
		if(Double.doubleToLongBits(money) < Double.doubleToLongBits(0)){
			throw new BizException("9990","充值金额不得小于0元");
		}
		//查询卡
		Card card = cardService.getCardByCCID(iccid, "0");
		if(card == null){
			throw new BizException("9990","iccid错误，未查询到此流量卡");
		}
		if(flowType == 0){//余额充值
			//生成支付宝预支付二维码
			AlipayUtil.getPayQRCodeImgUrl(money, orderId, iccid, iccid);
			c.setCreateTime(new Date(nowTime));
			c.setInvalidTime(new Date(invalidTime));
			c.setAmount(money);
			c.setPackId(0);
			c.setOrderId(orderId);
			c.setIccid(iccid);
			c.setPayType(0);
			c.setPkName("账户余额充值");
			c.setFlowType(0);
			cardRechargeFlowDao.insert(c);
		}else{
			if(pkgId == null){
				throw new BizException(RespCode.NOT_PARAM_ERROR);
			}
			//查询套餐所属的价格和卡的所属人
			OfficeCard officeCard = officeCardDao.selectThePeople(card.getId());
			if(officeCard == null){
				throw new BizException("9990","未查询到流量卡的所属人");
			}
			Package p = packageService.getTaocan2ByStoreid(officeCard.getOfficeId(), String.valueOf(pkgId));
			if(p == null){
				throw new BizException("9990","未查询到此卡的所属套餐价格");
			}
			System.out.println("===========================套餐id========"+p.getId());
			String title = p.getTctype();
			Double salePrice = p.getSalePrice();//销售价格
			BigDecimal data1 = new BigDecimal(money);
			BigDecimal data2 = new BigDecimal(salePrice);
			if(data1.compareTo(data2) == -1 || data1.compareTo(data2) == 1){
				throw new BizException("9990","充值金额和流量卡定价价格不一致");
			}
			//生成支付宝预支付二维码
			AlipayUtil.getPayQRCodeImgUrl(money, orderId, iccid, title);
			c.setCreateTime(new Date(nowTime));
			c.setInvalidTime(new Date(invalidTime));
			c.setAmount(money);
			c.setPackId(pkgId);
			c.setOrderId(orderId);
			c.setIccid(iccid);
			c.setPayType(0);
			c.setPkName(p.getTctype());
			c.setFlowType(1);
			cardRechargeFlowDao.insert(c);
		}
		//查询预订单是否成功
		CardRechargeFlow cardRechargeFlow = cardRechargeFlowDao.selectCardRechargeFlow(orderId);
		if(cardRechargeFlow == null){
			throw new BizException("9990","生成预订单失败");
		}
		map.put("pay_img_url", AlipayUtil.QR_CODE_IMG+orderId+".png");
		map.put("card_recharge_flow",cardRechargeFlow);
		return map;
	}
	
	public static void main(String[] args) {
		BigDecimal data1 = new BigDecimal(10);
		BigDecimal data2 = new BigDecimal(12);
		System.out.println(data1.compareTo(data2));
	}
	
	@Transactional(readOnly = false)
	public void updateByIccid(String iccid,Integer autoTopUp){
		if(StringUtils.isBlank(iccid) || autoTopUp == null){
			throw new BizException(RespCode.NOT_PARAM_ERROR);
		}
		if(autoTopUp.intValue() != 1 && autoTopUp.intValue() != 0){
			throw new BizException("9990","状态异常");
		}
		CardAmount ca = cardAmountDao.selectCardAmountByIccid(iccid);
		if(ca == null){
			throw new BizException("9990","未查询到iccid");
		}
		cardAmountDao.updateByIccid(iccid, autoTopUp);
	}
	
}